from django.shortcuts import render,redirect
from django.contrib.auth import login,logout
from django.contrib import messages
from .forms import UserRegisterForm,UserLoginForm,UserInfoChange
from .models import CustomerUser
from django.contrib.auth.decorators import login_required
from Chat.models import ChatRoom
# Create your views here.
def user_register(req):
    if req.method =='POST':
        form = UserRegisterForm(req.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(req,f'用户{username}注册成功，请登录')
            return redirect('User:login')
        else:
            return redirect('User:register')
    else:
        form = UserRegisterForm()
        return render(req,'User/register.html',{'form':form})


def user_login(req):
    if req.user.is_authenticated:
        return redirect('Chat:room_list')
    if req.method == 'POST':
        form = UserLoginForm(req,data=req.POST)
        if form.is_valid():
            user = form.get_user()
            login(req,user)
            if form.cleaned_data['remember_me']:  # 检查是否勾选
                req.session.set_expiry(24 * 60 * 60)  # 记住1天
            else:
                req.session.set_expiry(0)  # 关闭浏览器后失效
            messages.success(req,f'用户{user}欢迎回来')
            return redirect('Chat:room_list')
        messages.error(req,'账号或密码错误')
        return redirect('User:login')
    else:
        form = UserLoginForm()
        return render(req,'User/login.html',{'form':form})

@login_required
def user_logout(req):
    logout(req)
    messages.info(req,f'您已经成功登出')
    return redirect('User:login')

@login_required
def user_profile(req):
    if req.method =='POST':
        form = UserInfoChange(req.POST,req.FILES,instance=req.user)
        if form.is_valid():
            form.save()
            messages.success(req,f'{req.user}资料更新成功')
            return redirect('Chat:room_list')
        else:
            messages.error(req,'资料格式错误，请重新输入')
            return redirect('User:profile')
    else:
        form = UserInfoChange(instance=req.user)  # 要更改东西一定要传instance
        user_room = ChatRoom.objects.filter(creator=req.user).order_by('-create_time')
        return render(req,'User/profile.html',{'form':form,'user_room':user_room})

@login_required
def user_list(req):
    users = CustomerUser.objects.exclude(id=req.user.id).order_by('last_login')
    return render(req,'User/list.html', {'users': users})



